<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 调试控制器 - 用于调试Excel处理问题
 */
class Debug extends Controller
{
    /**
     * 简单的调试处理方法
     */
    public function processExcelData()
    {
        // 设置错误报告
        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        try {
            // 检查请求方法
            if ($this->request->isPost()) {
                $method = 'POST';
            } else {
                $method = 'GET';
            }

            // 简单测试数据
            $result = [
                'request_method' => $method,
                'timestamp' => date('Y-m-d H:i:s'),
                'categories_processed' => 0,
                'symptoms_processed' => 0,
                'formulas_processed' => 0,
                'errors' => []
            ];

            // 测试数据库连接
            try {
                $dbTest = Db::query('SELECT 1 as test');
                $result['db_connection'] = 'success';
            } catch (\Exception $e) {
                $result['db_connection'] = 'failed: ' . $e->getMessage();
                $result['errors'][] = 'Database connection failed';
            }

            // 测试基本处理逻辑
            try {
                // 简化的示例数据
                $sampleData = [
                    ['桂枝汤', '头痛', '发热', '头颈部症状'],
                    ['银翘散', '咳嗽', '咽痛', '呼吸系统症状']
                ];

                $result['sample_data_count'] = count($sampleData);
                $result['categories_processed'] = 1;
                $result['symptoms_processed'] = 3;
                $result['formulas_processed'] = 2;

            } catch (\Exception $e) {
                $result['errors'][] = 'Processing failed: ' . $e->getMessage();
            }

            // 返回JSON响应
            return json([
                'code' => 200,
                'msg' => '调试处理完成',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            // 错误处理
            return json([
                'code' => 500,
                'msg' => '调试失败: ' . $e->getMessage(),
                'data' => [
                    'error_trace' => $e->getTraceAsString()
                ]
            ]);
        }
    }

    /**
     * 测试JSON响应
     */
    public function testJson()
    {
        return json([
            'code' => 200,
            'msg' => 'JSON测试成功',
            'data' => [
                'timestamp' => date('Y-m-d H:i:s'),
                'test' => 'success'
            ]
        ]);
    }

    /**
     * 测试数据库操作
     */
    public function testDatabase()
    {
        try {
            // 测试数据库连接
            $result = Db::query('SELECT 1 as test');

            // 测试表查询
            $categories = Db::name('symptom_categories')->limit(5)->select();
            $symptoms = Db::name('symptoms')->limit(5)->select();
            $formulas = Db::name('formulas')->limit(5)->select();

            return json([
                'code' => 200,
                'msg' => '数据库测试成功',
                'data' => [
                    'connection' => 'success',
                    'categories_count' => count($categories),
                    'symptoms_count' => count($symptoms),
                    'formulas_count' => count($formulas),
                    'sample_category' => $categories[0] ?? null,
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '数据库测试失败',
                'data' => [
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]
            ]);
        }
    }

    /**
     * 测试翻译功能
     */
    public function testTranslation()
    {
        $translations = [
            'en' => [
                '头痛' => 'Headache',
                '咳嗽' => 'Cough',
                '桂枝汤' => 'Cinnamon Twig Decoction'
            ],
            'ja' => [
                '头痛' => '頭痛',
                '咳嗽' => '咳',
                '桂枝汤' => '桂枝湯'
            ]
        ];

        $testWords = ['头痛', '咳嗽', '桂枝汤'];
        $results = [];

        foreach ($testWords as $word) {
            $results[$word] = [
                'zh' => $word,
                'en' => $translations['en'][$word] ?? 'EN:' . $word,
                'ja' => $translations['ja'][$word] ?? 'JA:' . $word,
            ];
        }

        return json([
            'code' => 200,
            'msg' => '翻译测试成功',
            'data' => $results
        ]);
    }

    /**
     * 测试Excel文件读取
     */
    public function testExcelRead()
    {
        // 直接使用绝对路径
        $excelPath = 'F:/phpstudy_pro/intvale/ai_1/doc/sbb.xlsx';

        try {
            // 检查文件是否存在
            if (!file_exists($excelPath)) {
                return json([
                    'code' => 404,
                    'msg' => 'Excel文件不存在',
                    'data' => [
                        'path' => $excelPath,
                        'realpath' => realpath($excelPath)
                    ]
                ]);
            }

            // 读取Excel文件
            $spreadsheet = IOFactory::load($excelPath);
            $worksheet = $spreadsheet->getActiveSheet();
            $highestRow = $worksheet->getHighestRow();
            $highestColumn = $worksheet->getHighestColumn();

            $data = [];
            $validRowCount = 0;

            // 读取前10行作为示例
            for ($row = 1; $row <= min(10, $highestRow); $row++) {
                $rowData = [];
                $rowData['A'] = (string)$worksheet->getCell('A' . $row)->getValue(); // 汤药名称
                $rowData['B'] = (string)$worksheet->getCell('B' . $row)->getValue(); // 主证状
                $rowData['C'] = (string)$worksheet->getCell('C' . $row)->getValue(); // 兼症状
                $rowData['D'] = (string)$worksheet->getCell('D' . $row)->getValue(); // 所属分类

                $data[] = [
                    'row' => $row,
                    'data' => $rowData
                ];

                if (!empty($rowData['A']) && $row > 1) {
                    $validRowCount++;
                }
            }

            return json([
                'code' => 200,
                'msg' => 'Excel文件读取成功',
                'data' => [
                    'file_path' => $excelPath,
                    'file_exists' => true,
                    'file_size' => filesize($excelPath),
                    'total_rows' => $highestRow,
                    'highest_column' => $highestColumn,
                    'valid_rows' => $validRowCount,
                    'sample_data' => $data
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Excel文件读取失败',
                'data' => [
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]
            ]);
        }
    }

    /**
     * 调试首页
     */
    public function index()
    {
        echo "<!DOCTYPE html>";
        echo "<html lang='zh-CN'>";
        echo "<head><meta charset='UTF-8'><title>调试页面</title>";
        echo "<style>";
        echo "body { font-family: Arial, sans-serif; margin: 40px; }";
        echo ".btn { display: inline-block; padding: 10px 20px; margin: 10px; background: #007bff; color: white; text-decoration: none; border-radius: 5px; }";
        echo ".btn:hover { background: #0056b3; }";
        echo "</style>";
        echo "</head>";
        echo "<body>";
        echo "<h1>Excel处理系统调试页面</h1>";
        echo "<p><a href='/index/debug/testJson' class='btn'>测试JSON响应</a></p>";
        echo "<p><a href='/index/debug/testDatabase' class='btn'>测试数据库连接</a></p>";
        echo "<p><a href='/index/debug/testExcelRead' class='btn'>测试Excel文件读取</a></p>";
        echo "<p><a href='/index/debug/testTranslation' class='btn'>测试翻译功能</a></p>";
        echo "<p><a href='javascript:testAjax()' class='btn'>测试Ajax处理</a></p>";
        echo "<div id='result' style='margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 5px;'></div>";

        echo "<script>";
        echo "function testAjax() {";
        echo "  fetch('/index/debug/processExcelData', { method: 'POST' })";
        echo "    .then(response => response.json())";
        echo "    .then(data => {";
        echo "      document.getElementById('result').innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';";
        echo "    })";
        echo "    .catch(error => {";
        echo "      document.getElementById('result').innerHTML = '<p style=\"color: red;\">Error: ' + error.message + '</p>';";
        echo "    });";
        echo "}";
        echo "</script>";

        echo "</body>";
        echo "</html>";
    }
}